<template>
  <el-card class="card bottom">
    <el-divider content-position="left" style="margin: 5px 0 20px 0">
      <span style="font-weight: bold;color: #737373">复杂查询</span>
    </el-divider>
    <div class="t_box">

      <el-select v-model="queryForm.map.type_Id" placeholder="资产类别" class="t_item">
        <el-option
                v-for="item in assetType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="initAssetList"
        />
      </el-select>

      <el-select v-model="queryForm.map.sts" placeholder="资产状态" class="t_item">
        <el-option
                v-for="item in assetSts"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @click="initAssetList"
        />
      </el-select>

      <el-select v-model="queryForm.map.gmr" placeholder="购买人" class="t_item">
        <el-option
                v-for="item in selectGmrOptionData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click="initAssetList"
        />
      </el-select>

      <el-select v-model="queryForm.map.kcsl" placeholder="库存数量" class="t_item">
        <el-option
                v-for="o in 5"
                :key="o"
                :label="o*10"
                :value="o*10"
                @click="initAssetList"
        />
      </el-select>

      <div class="t_spitem">
        <el-date-picker
                v-model="queryForm.map.rksj"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="入库时间范围起始"
                end-placeholder="入库时间范围结束"
                size="default"
                @change="initAssetList"
        />
      </div>

      <div class="t_spitem">
        <el-date-picker
                v-model="queryForm.map.gmrq"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="购买时间范围起始"
                end-placeholder="购买时间范围结束"
                size="default"
                @change="initAssetList"
        />
      </div>

    </div>

  </el-card>

  <el-card class="card">
    <el-row :gutter="10" class="header">
      <el-col :span="4">
        <el-input placeholder="请输入资产名称..." v-model="queryForm.map.zcmc" clearable @clear="initClear"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input placeholder="请输入资产编号..." v-model="queryForm.map.zcbh" clearable @clear="initClear"></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" :icon="Search" @click="initAssetList">搜索</el-button>
      </el-col>
      <el-col :span="12">
        <div style="float: right">
          <el-button :icon="Setting" @click="showAll">重置</el-button>
          <el-button type="primary" :icon="Edit" @click="handleDialogValue">修改</el-button>
          <!--          <el-button type="danger" :icon="Delete" @click="handleDeleteSelect">删除</el-button>-->
          <el-button type="success" :icon="SoldOut" @click="exportExcel">导出Excel</el-button>
        </div>
      </el-col>
    </el-row>
    <el-table
            id="assets"
            ref="tableDataRef"
            :data="tableData"
            border stripe
            style="width: 100%"
            :cell-style="{textAlign: 'center'}"
            :header-cell-style="{textAlign: 'center'}"
            @selection-change="handleSelectionChange"
            @sort-change="sortChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="sts" label="状态" width="90" fixed>
        <template v-slot="scope">
          <el-tag size="default" v-if="scope.row.sts === 1" type="success" effect="dark">正常</el-tag>
          <el-tag size="default" v-else-if="scope.row.sts === 2" type="warning" effect="dark">损坏</el-tag>
          <el-tag size="default" v-else-if="scope.row.sts === 3" type="danger" effect="dark">报废</el-tag>
          <el-tag size="default" v-else-if="scope.row.sts === 4" effect="dark">调拨</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="rksj" label="入库时间" sortable="custom" width="130" fixed :formatter="formatDate"/>
      <el-table-column prop="zcbh" label="资产编号" width="130" fixed/>
      <el-table-column prop="zcmc" label="资产名称" width="120"/>
      <el-table-column prop="assetType" label="资产类别" width="150" :formatter="formatterAssetType"/>
      <el-table-column prop="zcxh" label="资产型号" width="85"/>
      <el-table-column prop="zcdj" label="资产单价" width="100"/>
      <el-table-column prop="zcje" label="资产金额" width="100"/>
      <el-table-column prop="sccj" label="生产厂家" width="150"/>
      <el-table-column prop="scrq" label="生产日期" sortable="custom" width="145" :formatter="formatDate"/>
      <el-table-column prop="gmrq" label="购买日期" sortable="custom" width="145" :formatter="formatDate"/>
      <el-table-column prop="gmr" label="购买人" width="100">
        <template #default="scope">
          <label v-if="scope.row.gmr==='1'">员工1</label>
          <label v-else-if="scope.row.gmr==='2'">员工2</label>
          <label v-else-if="scope.row.gmr==='3'">员工3</label>
        </template>
      </el-table-column>
      <el-table-column prop="kcsl" label="库存数量" sortable="custom" width="120"/>
      <el-table-column prop="cght" label="采购合同" width="250">
        <template v-slot="scope">
          <a target="_blank" :href="getServerUrl()+'contract/'+scope.row.cght">{{ scope.row.cght }}</a>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10,20,20,40,50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
  </el-card>

  <Dialog
          v-model="dialogVisible"
          :dialogVisible="dialogVisible"
          :dialog-title="dialogTitle"
          :ids="assetIds"
          @initAssetList="initAssetList"
          @resetAssetIds="resetAssetsIds"
  />
</template>

<script setup>
import { getCurrentInstance, ref } from 'vue';
import { Delete, Edit, Search, SoldOut, Setting } from '@element-plus/icons-vue';
import request, { getServerUrl } from "@/util/request";
import moment from 'moment';
import XLSX from 'xlsx'
import { ElMessage, ElMessageBox } from 'element-plus'
import Dialog from '@/views/page/assets/components/dialog'

/**
 * vue3中操作ref实例的写法（proxy代替this）
 */
const {proxy} = getCurrentInstance()

/**
 * 查询条件
 */
const queryForm = ref({
  map: {
    zcmc: "",
    zcbh: "",
    type_Id: "",
    sts: "",
    rksj: "",
    gmr: "",
    gmrq: "",
    kcsl: "",
  },
  pageNum: 1,
  pageSize: 10
})

const total = ref(0);//数据总数

const tableData = ref([]);//表格数据初始化

/**
 * 输入框清除
 */
const initClear = () => {
  proxy.$refs.tableDataRef.clearSort();
  initAssetList();
}

/**
 * 重置显示全部数据
 */
const showAll = () => {
  queryForm.value.map.zcmc = "";
  queryForm.value.map.type_Id = "";
  queryForm.value.map.sts = "";
  queryForm.value.map.rksj = "";
  queryForm.value.map.gmr = "";
  queryForm.value.map.gmrq = "";
  queryForm.value.map.kcsl = "";
  ids.value = [];
  initClear();
}

/**
 * 获取资产数据
 */
const initAssetList = async () => {
  const res = await request.post("asset/list", queryForm.value);
  console.log(res)
  tableData.value = res.data.assetList;
  total.value = res.data.total;
}
initAssetList();

/**
 * 初始化资产类别数据
 */
const assetType = ref([])

/**
 * 获取资产设备分类数据
 */
const initAssetTypeList = async () => {
  const res = await request.get("assetType/list");
  assetType.value = res.data.assetTypeList;
}
initAssetTypeList();

/**
 * 获取资产状态数据
 */
const initAssetStatus = async () => {
  const res = await request.get("status/list");
  formatterAStsList(res.data.statusList)
}
initAssetStatus();

/**
 * 初始化资产状态数据
 */
let assetSts = ref([]);

/**
 * 资产状态数据处理
 */
const formatterAStsList = (row) => {
  for (let i = 0; i < row.length; i++) {
    assetSts.value.push({value: row[i].id, label: row[i].name})
  }
}

const selectGmrOptionData = ref([])
const initAssetGmr = async () => {
  const res = await request.get("staff/listOffice");
  selectGmrOptionData.value = res.data.staffOfficeList;
}
initAssetGmr();

const id = ref(-1) //表格选中的数据id

const ids = ref([]) //表格选中数据的id集合

/**
 * 表格选中方法
 */
const handleSelectionChange = (selection) => {
  if (selection.length >= 1) {
    ids.value = selection;
  } else {
    ids.value = [];
  }
}

const assetIds = ref([]); //dialog传递变量（资产id数组）

const dialogTitle = ref(''); //资产修改框dialog

const dialogVisible = ref(false); //资产修改框dialog打开变量

/**
 * 打开修改dialog
 */
const handleDialogValue = () => {
  if (ids.value.length > 0) {
    ids.value.forEach((item) => {
      assetIds.value.push(item.id)
    })
    dialogTitle.value = "资产信息修改"
    dialogVisible.value = true;
  } else {
    ElMessage({
      message: '请选择一条数据',
      type: 'error',
    })
  }
}
/**
 * 重置assetsIds值
 */
const resetAssetsIds = () => {
  assetIds.value = [];
}

/**
 * 删除选择数据的方法
 */
const handleDeleteSelect = () => {
  if (id.value !== -1) {
    ElMessageBox.confirm(
            '确认删除这条数据吗?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
    )
            .then(async () => {
              const res = await request.post("asset/delete/" + id.value);
              console.log(res);
              if (res.data.code === 200) {
                ElMessage.success("删除成功")
              } else if (res.data.code === 500) {
                ElMessage.error(res.data.msg);
              }
            })
  } else {
    ElMessage.error("请选择一条数据")
  }
}

/**
 * 排序参数
 */
const sortQuery = ref({
  column: '',
  order: '',
  pageNum: 1,
  pageSize: 10,
})

/**
 * 排序的标识符
 */
const sort = ref(false);

/**
 * 根据字段排序的方法
 */
const sortChange = (column) => {
  sortQuery.value.column = column.prop;
  sortQuery.value.order = column.order;
  initSortList();
}

/**
 * 初始化字段排序
 */
const initSortList = async () => {
  const res = await request.post("asset/sort", sortQuery.value);
  sort.value = true;
  tableData.value = res.data.assetList;
  total.value = res.data.total;
}

/**
 * 当前页
 */
const currentPage = sort.value ? sortQuery.value.pageNum : queryForm.value.pageNum;

/**
 * 页容量
 */
const pageSize = sort.value ? sortQuery.value.pageSize : queryForm.value.pageSize;

/**
 * 处理每页记录数变化
 * @param pageSize
 */
const handleSizeChange = (pageSize) => {
  if (sort.value) {
    sortQuery.value.pageNum = 1;
    sortQuery.value.pageSize = pageSize;
    initSortList();
  } else {
    queryForm.value.pageNum = 1;
    queryForm.value.pageSize = pageSize;
    initAssetList();
  }
}

/**
 * 处理第几页变化
 * @param pageNum
 */
const handleCurrentChange = (pageNum) => {
  if (sort.value) {
    sortQuery.value.pageNum = pageNum;
    initSortList();
  } else {
    queryForm.value.pageNum = pageNum;
    initAssetList();
  }
}

/**
 * 格式化资产类别assetType数组信息
 * @param row
 * @returns {string}
 */
const formatterAssetType = (row) => {
  let assetTypeName = []
  for (let i = 0; i < row.assetType.length; i++) {
    assetTypeName.push(row.assetType[i].name)
  }
  return assetTypeName.join()
}

/**
 * 表格通用格式化时间信息
 * @param row
 * @param column
 * @returns {string}
 */
const formatDate = (row, column) => {
  let date = row[column.property];
  if (date === undefined) {
    return "";
  }
  return moment(date).format("YYYY-MM-DD");
  // return moment(date).format("YYYY/MM/DD");
}

/**
 * 通用格式化时间信息
 * @param data
 * @returns {string}
 */
const currencyFormatDate = (data) => {
  let date = data;
  if (date === undefined) {
    return "";
  }
  return moment(date).format("YYYY-MM-DD");
}

/**
 * 表格数据导出Excel实际方法
 * @param list
 */
const exportList = (list) => {
  //定义表头内容
  let tableHeader = [[
    '#', '资产编号', '资产名称', '资产类别', '资产型号', "资产单价",
    "资产金额", "生产厂家", "生产日期", "购买日期", "购买人", "状态", "库存数量"
  ]]
  //参数遍历添加内容
  list.forEach((item, index) => {
    let rowData = []
    //导出内容的字段
    rowData = [
      index + 1, item.zcbh, item.zcmc, item.name,
      item.zcxh, item.zcdj, item.zcje, item.sccj,
      currencyFormatDate(item.scrq),
      currencyFormatDate(item.gmrq),
      item.gmr, item.sts, item.kcsl,
    ]
    tableHeader.push(rowData)
  })
  //创建excel文件
  let ws = XLSX.utils.aoa_to_sheet(tableHeader)
  let wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '资产设备基本信息') //工作簿名称
  XLSX.writeFile(wb, '资产设备基本信息.xlsx') //保存的文件名
}

//导出
const exportVariable = ref({
  title: "确认导出全部数据吗",
  idArray: [],
  dataList: [],
})

//重置excel基本变量
const resetExportVariable = () => {
  exportVariable.value.title = "确认导出全部的数据吗";
  exportVariable.value.idArray = [];
  exportVariable.value.dataList = [];
}

/**
 * 表格数据导出Excel调用方法
 */
const exportExcel = async () => {
  //首先判断导出全部数据还是导出选中的数据
  //如果定义选中数据的id数组不为空执行如下的if语句重新赋值
  if (ids.value.length !== 0) {
    ids.value.forEach((item) => {
      exportVariable.value.idArray.push(item.id)
    })
    console.log(exportVariable.value.idArray)
    //改变提示信息
    exportVariable.value.title = "确认导出选中的数据吗"
    //根据id数组查询数据
    const res = await request.post("asset/listById", exportVariable.value.idArray);
    //赋值给传参数组
    exportVariable.value.dataList = res.data.assetList;
  }
  ElMessageBox.confirm(
          exportVariable.value.title,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(async () => {
            //判断传参数组是否为空
            if (exportVariable.value.dataList.length === 0) {
              //为空导出全部数据
              const res = await request.get("asset/listAll");
              exportList(res.data.assetsAllList);
            } else {
              //不为空导出选中的数据
              exportList(exportVariable.value.dataList);
              resetExportVariable();
            }
            ElMessage.success("导出成功")
          })
          .catch(() => {
            //消息提示框点击取消或者关闭重置导出excel基本变量
            resetExportVariable();
          })
}
</script>

<style lang="scss" scoped>
.header {
  box-sizing: border-box;
  margin-bottom: 15px;
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

::v-deep th.el-table__cell {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 15px;
}

.el-tag--small {
  margin-left: 5px;
}

.card {
  border: none;
  border-radius: 0;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.top {
  margin-top: 10px;
}

.bottom {
  margin-bottom: 10px;
}

.t_box {
  display: flex;
  align-items: center;

  .t_item {
    flex: 1;
    width: 60px;
    margin-right: 15px;
  }

  .t_spitem {
    margin-right: 15px;
  }
}

//::v-deep .el-table__header-wrapper .el-checkbox {
//  //找到表头那一行，然后把里面的复选框隐藏掉
//  display: none
//}
</style>